﻿using System;
using System.Collections.Generic;
using System.Text;
using Tauren.File.Entity.Model;
using Tauren.File.Infrastructure.Globals;
using Dapper;
using Dapper.Contrib.Extensions;
using System.Linq;
using Tauren.File.Entity.Output;
using Tauren.File.Entity.Global;

namespace Tauren.File.DLL.FolderDLL
{
    public class FileFolderBusiness : Base.BaseDLL, IFileFolderBusiness
    {
        public FileFolderBusiness(IConnectionDLLBase _dLLBase) : base(_dLLBase)
        {

        }

        /// <summary>
        /// 添加前先关闭
        /// </summary>
        /// <param name="modele"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public bool Edit() => this.BusinessConnection.Execute(sql: "UPDATE Physicalhistory  SET `enable`=0 WHERE `enable`=1") >= 0;

        public List<FileFolder> GetFolders(int pid) => this.BusinessConnection.Query<FileFolder>(sql: "SELECT *  FROM   filefolder WHERE   parentId=@ParentId", param: new FileFolder() { ParentId = pid }).AsList();

        public List<FileFolder> GetListOrgID(int orgId, string type) => this.BusinessConnection.Query<FileFolder>(sql: "SELECT *  FROM   filefolder WHERE orgid=@OrgId and flodertype=@FloderType and parentId=0", param: new FileFolder() { OrgId = orgId, FolderType = type }).AsList();

        public double GetSeq()
        {
            FileFolder floder = this.BusinessConnection.QueryFirstOrDefault<FileFolder>("SELECT * FROM filefolder WHERE havedelete=0  ORDER BY autoid DESC LIMIT 0,1");
            if (floder is null) return 1;
            else return (floder.Sequence is null ? 1 : floder.Sequence.Value + 1);
        }

        public bool IsFolderRepeat(FileFolder filefolder)
        {
            StringBuilder sqlScript = new StringBuilder("select * from filefolder f where (cnname =@CNName or enname =@ENName) AND ParentId=@ParentId");
            if (filefolder.AutoId > 0)
                sqlScript.Append("  and  autoId != @AutoId");
            List<FileFolder> floders = this.BusinessConnection.Query<FileFolder>(sql: sqlScript.ToString(), param: filefolder).AsList();
            if (floders.Any()) return true;
            else return false;
        }

        public List<FileFolder> List(object id) => this.BusinessConnection.Query<FileFolder>(sql: "SELECT *  FROM  filefolder WHERE autoid=@AutoId", param: new FileFolder() { AutoId = (int)id }).AsList();

        public List<PageDocumentCenterTable> Pages(QueryModel queryModel, out long Total)
        {

            Total = 0;
            string where = "";
            string floderWhere = @$"select
                                autoId,
                                cnname,
                                enname,

                                '' as ext,
		                        0 filetype,
		                        foldertype OrgType,

                                '' size,
		                        '' CurrentVersion,
		                        `sequence`,
		                        path,
		                        OrgId,
		                        '' FileUri,
		                        havedelete,creatdate,creator,enable
                            from

                                filefolder f where havedelete!=1 ";
            string fileWhere = @"union select
                                        autoId,
		                                cnname ,
		                                enname,
		                                ext,
		                                filetype,
		                                '' OrgType,
		                                size,
		                                currentVersion,
		                                `sequence` ,
		                                `path` ,
		                                0 orgid ,
		                                fileuri,
		                                havedelete,creatdate,creator,enable
                                    from

                                        files f2 where havedelete!=1 ";
            if (!string.IsNullOrEmpty(queryModel.KeyWord))
            {
                where += $"   AND (t.cnname LIKE '%{queryModel.KeyWord}%'  OR t.enname LIKE '%{queryModel.KeyWord}%' )  ";
            }
            if (queryModel.paramters.Any(o => o.Label.ToLower() == "orgid") && queryModel.paramters.Any(o => o.Label.ToLower() == "foldertype"))
            {
                var orgId = queryModel.paramters.FirstOrDefault(P => P.Label.ToLower() == "orgid");
                var folder = queryModel.paramters.FirstOrDefault(p => p.Label.ToLower() == "foldertype");
                if (!string.IsNullOrEmpty(orgId.Value + "") && !string.IsNullOrEmpty(folder.Value + ""))
                    floderWhere += @$" AND orgid={orgId.Value} and foldertype={folder.Value}";
            }
            if (queryModel.paramters.Any(o => o.Label.ToLower() == "folderid"))
            {
                var floder = queryModel.paramters.FirstOrDefault(P => P.Label.ToLower() == "folderid");
                if (!string.IsNullOrEmpty(floder.Value + "") && (floder.Value + "") != "0")
                {
                    floderWhere += $" AND parentId= {floder.Value}    ";
                    fileWhere += $" AND folderid ={ floder.Value}    ";
                }
                else
                {
                    floderWhere += $" AND parentId= 0   ";
                    fileWhere = "";
                }
            }
            var paramtets = queryModel.paramters.Where(o => o.Label.ToLower() != "orgid" && o.Label.ToLower() != "foldertype"&& o.Label.ToLower() != "folderid").ToList();
            paramtets.ForEach(p =>
            {
                where += $"  and {p.Label} like '%{p.Value}%'  ";
            });

            if (queryModel.KeyWords.Any(o => o.Label.ToLower() == "orgid") && queryModel.KeyWords.Any(o => o.Label.ToLower() == "foldertype"))
            {
                var orgId = queryModel.KeyWords.FirstOrDefault(P => P.Label.ToLower() == "orgid");
                var folder = queryModel.KeyWords.FirstOrDefault(p => p.Label.ToLower() == "foldertype");
                if (!string.IsNullOrEmpty(orgId.Value + "") && !string.IsNullOrEmpty(folder.Value + ""))
                    floderWhere += @$" AND orgid={orgId.Value} and foldertype={folder.Value}";
            }
            if (queryModel.KeyWords.Any(o => o.Label.ToLower() == "folderid"))
            {
                var floder = queryModel.KeyWords.FirstOrDefault(P => P.Label.ToLower() == "folderid");
                if (!string.IsNullOrEmpty(floder.Value + "") && (floder.Value + "") != "0")
                {
                    floderWhere += $" AND parentId= {floder.Value}    ";
                    fileWhere += $" AND folderid ={floder.Value}    ";
                }
                else
                {
                    floderWhere += $" AND parentId= 0   ";
                    fileWhere = "";
                }
            }
            if (string.IsNullOrEmpty(queryModel.SortField))
            {
                queryModel.SortField = "sequence";
                queryModel.IsAsc = false;
            }
            else
            {
                queryModel.SortField = queryModel.SortField.ToLower().Replace("dic_", "").Replace("dic", "").Trim();
            }
            if (!queryModel.UseDisabledData)
            {
                where += $" AND enable=1  ";
            }
            string asc = queryModel.IsAsc ? "ASC" : "DESC";
            queryModel.Page = queryModel.Page == 0 ? 1 : queryModel.Page;
            StringBuilder sql = new StringBuilder();
            sql.Append(@$"SELECT count(t.autoid) from ({floderWhere}  { fileWhere} )t  WHERE t.havedelete!=1  {where} ;");
            sql.Append(@$" SELECT * FROM ({floderWhere}  { fileWhere} )t WHERE havedelete!=1
                        {where}  ORDER BY t.{queryModel.SortField} {asc} LIMIT {(queryModel.Page - 1) * queryModel.PageSize},{ queryModel.PageSize} ;");
            using (var reader = this.BusinessConnection.QueryMultiple(sql.ToString()))
            {
                Total = reader.ReadFirstOrDefault<int>();
                List<PageDocumentCenterTable> pageModules = reader.Read<PageDocumentCenterTable>().ToList();
                long RowNo = ((queryModel.Page == 0 ? 1 : queryModel.Page) - 1) * queryModel.PageSize + 1;
                pageModules.ForEach(o =>
                {
                    o.RowNo = RowNo;
                    RowNo++;
                });
                return pageModules;
            }
        }

        /// <summary>
        /// 获取最新的文件夹
        /// </summary>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public Physicalhistory SingleByEnable() => this.BusinessConnection.QueryFirstOrDefault<Physicalhistory>("SELECT * FROM Physicalhistory where `enable`=1 order by autoid desc LIMIT 0,1");
    }
}
